import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:novel_reader/api/baidu_api.dart';
import 'package:novel_reader/api/fish_hawk_api.dart';
import 'package:novel_reader/utils/utils.dart';

part 'chapter.g.dart';

@HiveType(typeId: 0)
class Chapter {
  @HiveField(0)
  String bookCode;

  @HiveField(1)
  String chapterId;

  @HiveField(2)
  String? title;

  @HiveField(3)
  String? titleJp;

  @HiveField(4)
  String? update;

  @HiveField(5)
  String? content;

  @HiveField(6)
  String? translation;

  @HiveField(7)
  int? order;

  int index = 0;

  Chapter({
    required this.bookCode,
    required this.chapterId,
    this.title,
    this.titleJp,
    this.update,
    this.content,
    this.translation,
    this.order,
  });

  Future<String?> getTranslation(bool? refresh, Function? onUpdated) async {
    if (refresh! || Utils.isEmpty(translation)) {
      String? temp = translation;
      if (refresh) {
        translation = null;
      }
      bool callUpdate = await FishHawkApi.initChapter(this);
      if (Utils.isEmpty(translation) && !Utils.isEmpty(content)) {
        try {
          translation = await BiaduApi.baiduTranslate(content!);
          if (onUpdated != null && !Utils.isEmpty(translation)) {
            callUpdate = false;
            onUpdated();
          }
        } catch (e) {
          debugPrint('getTranslation error:$e');
        }
      }
      if (refresh && Utils.isEmpty(translation)) {
        translation = temp;
      }
      if (callUpdate && onUpdated != null) {
        onUpdated();
      }
    }
    return translation;
  }

  @override
  String toString() {
    if (index > 0) {
      return '$index：$title';
    }
    return '$title';
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Chapter &&
          runtimeType == other.runtimeType &&
          bookCode == other.bookCode &&
          chapterId == other.chapterId;

  @override
  int get hashCode => bookCode.hashCode ^ chapterId.hashCode;
}
